﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Reflection;

namespace PowerPatcher
{
	class PlugInHost 
    {
        public Collection<PowerPatcherInterop.iPlugIn> PlugIns { get; private set; }
        private MainWindow _window;

        private Dictionary<PowerPatcherInterop.iPlugIn, string> pathTable;

        public PlugInHost(MainWindow window)
        {
        	_window = window;
        	
        	string addInRoot = Environment.CurrentDirectory + "\\Extentions\\Addins";
        	_window.UpdateMainProg(0, PowerPatcher.Msgs.LoacatingAddins);
        	Helper.WriteLogLine("Locating addins. Base: " + addInRoot);
        	
        	List<string> files = Helper.GetDLLFiles(addInRoot, true);

            int LoadCount = 0;
            pathTable = new Dictionary<PowerPatcherInterop.iPlugIn, string>();
            PlugIns = new Collection<PowerPatcherInterop.iPlugIn>();
            foreach (string s in files)
            {
                Helper.WriteLogLine("Loading assembly [" + LoadCount + "] " + s);
                _window.UpdateMainProg(LoadCount / (double)files.Count, string.Format(PowerPatcher.Msgs.LoadingAssemblyX0X1X2, System.IO.Path.GetFileName(s), LoadCount, files.Count));
                LoadPlugIn(s);
                LoadCount++;
            }
        }
        private void LoadPlugIn(string file)
        {
        	try
        	{
                byte[] b;
                using (System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open))
                {
                    b = new byte[fs.Length];
                    fs.Read(b, 0, (int)fs.Length); 
                }
                Assembly a = Assembly.Load(b);
        		Type[] types = a.GetTypes();
        		foreach (Type t in types)
        		{
        			if (t.GetInterface("iPlugIn") != null)
        			{
        				lock(PlugIns)
        				{
                            PowerPatcherInterop.iPlugIn plug = (PowerPatcherInterop.iPlugIn)System.Activator.CreateInstance(t);
        					PlugIns.Add(plug);
        					pathTable.Add(plug, file);
        				}
        			}
        		}
        	}
        	catch (Exception ex)
        	{
        		Helper.WriteLogLine("ERROR: " + ex.GetType().Name + " occured while attemping to load " + file + ". " + ex.Message);
        	}
        }

        public string GetPlugPath(PowerPatcherInterop.iPlugIn Plug)
        {
            return pathTable[Plug];
        }
    }
}
